package org.thotheolh.db2json.db;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.json.JSONWriter;
import org.thotheolh.db2json.db.struct.Element;
import org.thotheolh.db2json.db.struct.Table;
import org.thotheolh.db2json.db.struct.Tuple;

public class DbCodec {

	private JSONArray tupleJA;
	private JSONArray tableJA;
	private JSONArray dbJA;
	private JSONObject tableJO;
	private JSONObject elementJO;

	public DbCodec() {

	}

	/**
	 * Converts logical tables into JSON format
	 * 
	 * @param tableList
	 */
	private void encodeToJson(ArrayList<Table> tableList) {
		try {
			dbJA = new JSONArray();
			for (int h = 0; h < tableList.size(); h++) {
				Table table = tableList.get(h);
				tableJO = new JSONObject();
				tableJA = new JSONArray();
				tableJO.put(table.getTableName(), tableJA);
				ArrayList<Tuple> tupleList = table.getTuples();
				for (int i = 0; i < tupleList.size(); i++) {
					Tuple tuple = tupleList.get(i);
					tupleJA = new JSONArray();
					for (int j = 0; j < tuple.size(); j++) {
						Element element = tuple.get(j);
						if (element.getKey() == null) {
							// Directly inserts into tuple array
							if (tupleJA != null) {
								tupleJA.put(element.getValue());
							}
						} else {
							// Creates an element to insert into tuple array
							elementJO = new JSONObject().put(element.getKey(),
									element.getValue());
							if (tupleJA != null) {
								tupleJA.put(elementJO);
							}
						}
					}
					if (tableJA != null) {
						tableJA.put(tupleJA);
					}
				}
				if (dbJA != null) {
					dbJA.put(tableJO);
				}
			}
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Converts and output table structure to JSON file
	 * 
	 * @param tableList
	 * @param output
	 */
	public void toJson(ArrayList<Table> tableList, File output) {
		try {
			if (!output.exists()) {
				output.createNewFile();
			}
			FileWriter fw = new FileWriter(output);
			JSONWriter writer = new JSONWriter(fw);
			encodeToJson(tableList);
			System.out.println("DBJA:-" + dbJA.toString());
			System.out.println("File:-" + output.exists());
			writer.object().key("DB").value(dbJA).endObject();
			fw.flush();
			fw.close();
			System.out.println("Done !");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	/**
	 * Converts JSON to logical tables
	 * 
	 * @param input
	 */
	public void fromJson(String input) {

	}
}
